import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

function inspectClient(){
  return window.innerWidth < 800
}

// const 转 动态函数
const getDefaultState = () => {
  return {
    token: getToken(),
    isMobile: inspectClient(),
    username: 'admin',
    password: 'admin',
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    // 重置刷新state 函数化  代码块重新走一遍
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_IDENTIFY: (state, userInfo) => {
    const { username, password, } = userInfo
    state.username = username
    state.password = password
  },
  clearToken: (state, token) => {
    state.token = token
  },
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    // const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login(userInfo).then(response => {
        console.log(response)
        const { access_token } = response
        // commit('SET_TOKEN', access_token)
        commit('SET_IDENTIFY', userInfo)
        setToken(access_token)
        commit("RESET_STATE")
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, rootState, rootGetters, }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        // 刷新Vuex.Store
        commit('RESET_STATE')
        // 通过root访问其他模块的东西, 默认是在当前模块扫描 检索
        commit("info/set_perm", "", { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit, state, }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit("RESET_STATE")
      commit("info/reset_state", null, { root: true })
      resolve()
    })
  },

  // 重置数据
  resetState({ commit, state}) {
    return new Promise(resolve => {
      removeToken()
      commit("RESET_STATE")
      commit("info/reset_state", null, {root: true})
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
